﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using MyLib;
using Portal.Entity;
//using Portal.Interface;
using Portal.Logic;
using ProcessControl;
using ProcessControl.Interface;
using ProcessControl.Entity;
using System.Collections;
using Portal.Interface;

namespace PRProcess
{
    public partial class NewPRProcess : System.Web.UI.Page
    {
        ICapex capex = ServiceContainer.Instance().GetService<ICapex>();
        IOrg _org = ServiceContainer.Instance().GetService<IOrg>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
                //加载大类
                ResourceLogic rl = new ResourceLogic();
                List<ResourceEntity> lRe = rl.GetResourceList("Catagory");
                this.CATAGARY.DataSource = lRe;
                CATAGARY.DataBind();
                //foreach (ResourceEntity re in lRe)
                //{ 
                //    this.fld_CATAGARY.Items.Add(new ListItem(re.CNNAME,re.))
                //}

            }
            UserEntity user = _org.GetUserEntity(Portal.Logic.SSOLogic.GetLoginName());
            string strUserDept = user.EXT02;
            string strCostCenter = InitCostCenter(user.USERID, user.EXT02);
            fld_ISOPERATION.Text = JudgeIsOpreation(strCostCenter);

            ((ButtonList)this.ButtonList1).AfterSubmit += new System.ComponentModel.CancelEventHandler(NewPRProcess_AfterSubmit);
        }

        void NewPRProcess_AfterSubmit(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //throw new NotImplementedException();
            //更新余额
            IBuget buget = ServiceContainer.Instance().GetService<IBuget>();
            string CapexNo = this.fld_CERNO.Text.Trim();
            string strFormID = GetCapexFormID(CapexNo);
            foreach (RepeaterItem ri in fld_detail_PROC_PURCHASEREQUEST_DT.Items)
            {
                string bugCode = ((TextBox)ri.FindControl("fld_ITEMNUMBER")).Text;
                double amount = ConvertUtil.ToDouble(((TextBox)ri.FindControl("fld_ESTIMATEDPRICE")).Text);
                string Msg;
                if (!buget.UpdateBalaceFromPR(bugCode, amount, out Msg))
                {
                    LogUtil.Info("更新预算号" + bugCode + "失败：" + Msg);
                }
                if (CapexNo != "")   //如果当前用户有选择Capex单号
                {
                    bool IsSuccess = capex.UpdateRowsStatus(bugCode, strFormID);   //根据当前用户选择的Capex，更新Capex行数据的Status为2（0为初始值，1为已经提交审批过的）
                }
            }

        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            UserInfo userInfo = Page.FindControl("UserInfo1") as UserInfo;
            userInfo.AddNewRow(fld_detail_PROC_PURCHASEREQUEST_DT);
        }


        protected void fld_detail_PROC_PURCHASEREQUEST_DT_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            UserInfo userInfo = Page.FindControl("UserInfo1") as UserInfo;
            userInfo.DeleteRow(fld_detail_PROC_PURCHASEREQUEST_DT, e);
        }

        protected void fld_CATAGARY_SelectedIndexChanged(object sender, EventArgs e)
        {

            DropDownList ddlCategory = sender as DropDownList;
            fld_CATAGARY.Text = ddlCategory.SelectedItem.Text;
            int selectCatagory = ConvertUtil.ToInt32(ddlCategory.SelectedValue);
            hfselectCatagory.Value = selectCatagory.ToString();
            //fld_SUBCATAGARY.Items.Clear();
            //fld_SUBCATAGARY.Items.Insert(0, new ListItem("---请选择小类---", ""));
            //if (selectCatagory != 0)
            //{
            //    ResourceLogic resLogic = new ResourceLogic();
            //    List<ResourceEntity> listResAll = resLogic.GetResourceList();
            //    //筛选子节点

            //    this.fld_SUBCATAGARY.DataSource = listResAll.FindAll(p => p.PARENTID == selectCatagory);
            //    this.fld_SUBCATAGARY.DataBind();
            //}
        }
        protected void fld_CAPEX_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddlCur = (DropDownList)sender;
            TextBox txtCurBgNumber = (TextBox)ddlCur.Parent.FindControl("fld_ITEMNUMBER");
            txtCurBgNumber.Text = ddlCur.SelectedValue;

            TextBox txtSelectCapexItem = (TextBox)ddlCur.Parent.FindControl("fld_CAPEXITEM");
            txtSelectCapexItem.Text = ddlCur.SelectedItem.Text;
            //获取预算编号的余额
            TextBox txtCurBalance = (TextBox)ddlCur.Parent.FindControl("fld_BALANCE");
            txtCurBalance.Text = ConvertUtil.ToString(capex.GetBugetBalace(txtCurBgNumber.Text));
            // txtCurBalance.ReadOnly = true;
            // txtCurBgNumber.ReadOnly = true;
            txtCurBalance.Attributes.Add("disInput", "true");
            txtCurBgNumber.Attributes.Add("disInput", "true");
        }
        protected void fld_detail_PROC_PURCHASEREQUEST_DT_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {


            //RepeaterItem currentItem = e.Item;
            //string cerNo = this.fld_CERNO.Text.Trim();
            //DropDownList ddlCurrentCapex = currentItem.FindControl("CAPEXITEM") as DropDownList;
            //if (string.IsNullOrEmpty(cerNo) || cerNo == "")
            //{
            //    ddlCurrentCapex.Enabled = false;
            //}
            //else
            //{
            //    ddlCurrentCapex.Attributes.Remove("OnSelectedIndexChanged");
            //    ddlCurrentCapex.Items.Clear();
            //    ddlCurrentCapex.Items.Insert(0, new ListItem("---请选择---", ""));
            //    List<CapexDetailEntity> lstCapexDetail = capex.GetCapexDetailByCapexNO(cerNo);
            //    foreach (CapexDetailEntity cde in lstCapexDetail)
            //    {
            //        ddlCurrentCapex.Items.Add(new ListItem(cde.ProjectName, cde.BudgetNumber));
            //    }
            //}

        }

        protected void fld_detail_PROC_PURCHASEREQUEST_DT_PreRender(object sender, EventArgs e)
        {
            foreach (RepeaterItem ri in this.fld_detail_PROC_PURCHASEREQUEST_DT.Items)
            {
                RepeaterItem currentItem = ri;
                string cerNo = this.fld_CERNO.Text.Trim();
                DropDownList ddlCurrentCapex = currentItem.FindControl("CAPEXITEM") as DropDownList;
                if (string.IsNullOrEmpty(cerNo) || cerNo == "")
                {
                    ddlCurrentCapex.Enabled = false;
                }
                else
                {
                    ddlCurrentCapex.Attributes.Remove("OnSelectedIndexChanged");
                    ddlCurrentCapex.Items.Clear();
                    ddlCurrentCapex.Items.Insert(0, new ListItem("---请选择---", ""));
                    List<CapexDetailEntity> lstCapexDetail = capex.GetCapexDetailByCapexNO(cerNo);
                    foreach (CapexDetailEntity cde in lstCapexDetail)
                    {
                        ddlCurrentCapex.Items.Add(new ListItem(cde.ProjectName, cde.BudgetNumber));
                    }
                }
                UserInfo userInfo = Page.FindControl("UserInfo1") as UserInfo;              

                DropDownList ddlCurrent = ((DropDownList)ri.FindControl("CAPEXITEM"));

                string selectText = ((TextBox)ri.FindControl("fld_CAPEXITEM")).Text;
                if (selectText != "")
                {
                    ddlCurrent.Items.FindByText(selectText).Selected = true;
                }

                
                //绑定小类信息
                DropDownList ddlSUBCATAGARY = currentItem.FindControl("SUBCATAGARY") as DropDownList;
                ddlSUBCATAGARY.Items.Clear();
                if (userInfo.Incident != "0")  
                {
                    ddlSUBCATAGARY.AppendDataBoundItems = false;   //在数据绑定之前添加一个"请选择小类"信息
                }
                ddlSUBCATAGARY.Items.Insert(0, new ListItem("---请选择小类---", ""));
                int selectCatagory = int.Parse(hfselectCatagory.Value);                
                if (selectCatagory != 0)
                {
                    ResourceLogic resLogic = new ResourceLogic();
                    List<ResourceEntity> listResAll = resLogic.GetResourceList();
                    //筛选子节点                   
                    ddlSUBCATAGARY.DataSource = listResAll.FindAll(p => p.PARENTID == selectCatagory);
                    ddlSUBCATAGARY.DataBind();
                }
                
                //DropDownList ddlSub = ((DropDownList)ri.FindControl("SUBCATAGARY"));
                DropDownList ddlCostCategory = ((DropDownList)ri.FindControl("COSTCATEGORY"));

                //string selectSubcatagaryText = ((TextBox)ri.FindControl("fld_SUBCATAGARY")).Text;
                string selectCostCategory = ((TextBox)ri.FindControl("fld_COSTCATEGORY")).Text;
                //if (selectSubcatagaryText != "")
                //{
                //    ddlSub.Items.FindByText(selectSubcatagaryText).Selected = true;
                //}
                if (selectCostCategory != "")
                {
                    ddlCostCategory.ClearSelection(); 
                    ddlCostCategory.Items.FindByText(selectCostCategory).Selected = true;
                }
            }
        }

        protected void CATAGARY_PreRender(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DropDownList dll = (DropDownList)sender;
                string txt = ((TextBox)dll.Parent.FindControl("fld_CATAGARY")).Text;
                if (txt.Trim() != "")
                {
                    dll.Items.FindByText(txt).Selected = true;
                }
                fld_CATAGARY_SelectedIndexChanged(sender, e); 
            }
        }

        /// <summary>
        /// 初始化成本中心
        /// </summary>
        /// <param name="UesrID"></param>
        /// <returns></returns>
        public string InitCostCenter(int UesrID, string strDept)
        {
            string strCostCenter = "";
            DataTable dt_detail = null;
            string strSql = "select EXT01 from COM_USER where USERID=" + UesrID + "";
            dt_detail = DataAccess.Instance("BizDB").ExecuteDataTable(strSql);
            if (dt_detail.Rows.Count > 0)
            {
                strCostCenter = dt_detail.Rows[0]["EXT01"].ToString().Trim();
            }
            return strCostCenter;
        }

        /// <summary>
        /// 获取当前成本中心是否属于运营部门，1代表是，0代表否
        /// </summary>
        /// <param name="strCostCenter"></param>
        /// <returns></returns>
        public string JudgeIsOpreation(string strCostCenter)
        {
            string strResult = "";
            DataTable dt = null;
            string strSql = "SELECT COSTCENTERNUMBER, COSTCENTERNAME, DEPTID, DEPTNAME, ISOPERATION FROM SYNC_COSTCENTER WHERE (COSTCENTERNUMBER = '" + strCostCenter.Trim() + "') AND (ISOPERATION = '1')";
            dt = DataAccess.Instance("BizDB").ExecuteDataTable(strSql);
            if (dt.Rows.Count > 0)
            {
                strResult = "1";
            }
            else
            {
                strResult = "0";
            }
            return strResult;
        }

        /// <summary>
        /// 根据当前用户选择的Capex单号，返回Capex的主FormID
        /// </summary>
        /// <param name="CapexNo"></param>
        /// <returns></returns>
        public string GetCapexFormID(string CapexNo)
        {
            string strResult = "";
            try
            {
                DataTable dt = null;
                string strSql = "select FORMID from PROC_CAPEX where DOCUMENTNO='" + CapexNo.Trim() + "'";
                dt = DataAccess.Instance("BizDB").ExecuteDataTable(strSql);
                if (dt.Rows.Count > 0)
                {
                    strResult = dt.Rows[0]["FORMID"].ToString().Trim();
                }
            }
            catch (Exception ex)
            {
                string strMessage = ex.Message;
            }
            return strResult;
             
        }
    }
}